package com.xinxin.o2o.controller.commoncontroller;

import com.google.code.kaptcha.Producer;
import com.xinxin.o2o.response.Response;
import com.xinxin.o2o.util.ResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Map;

/**
 * @author ShiXinXin
 * @date 2019-09-07 14:40
 */
@Api(tags = {"公共模块"}, produces = "application/json")
@RestController
@RequestMapping("/api/common")
public class CommonController {
    private Logger logger = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private Producer captchaProducer;

    @ApiOperation(value = "获取验证码")
    @GetMapping("/verifyCode")
    public void verifyCode(HttpServletResponse httpServletResponse, HttpSession httpSession) throws Exception {
        logger.info("===verifyCode:" + httpSession.getId() + "===");
        byte[] captchaChallengeAsJpeg;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = captchaProducer.createText();
            httpSession.setAttribute("verifyCodeExpected", createText.toLowerCase());
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = captchaProducer.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }


    @ApiOperation(value = "校验验证码")
    @PostMapping("/checkVerifyCode")
    public Response checkVerifyCode(@RequestBody Map<String, String> map, HttpSession httpSession) {
        logger.info("===checkVerifyCode:" + httpSession.getId() + "===");
        String verifyCodeActual = map.get("verifyCodeActual").toLowerCase();
        String verifyCodeExpected = (String) httpSession.getAttribute("verifyCodeExpected");
        logger.info("verifyCodeExpected:" + verifyCodeExpected + " verifyCodeActual:" + verifyCodeActual);
        return ResponseUtil.success(verifyCodeActual.equals(verifyCodeExpected));
    }
}
